/*
 *  AudioEngineIPhone.mm
 *  SypXIPhone
 *
 *  Created by Luv Khemani on 7/24/10.
 *  Copyright 2010 Luv Khemani. All rights reserved.
 *
 */


#import <UIKit/UIKit.h>

//OpenAL includes to handle audio interruptions
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <AL/alut.h>

#include "Engine.h"
#include "AudioEngineIPhone.h"
#include "ErrorLogger.h"

namespace SypX
{
	AudioEngineIPhone::AudioEngineIPhone():audioPlayer(0)
	{
	}
	
	AudioEngineIPhone::~AudioEngineIPhone()
	{
		if(audioPlayer)
		{
			[audioPlayer stop];
			[audioPlayer release];
		}
	}
	void AudioEngineIPhone::playMusic(const String& file, bool loop)
	{
		if(audioPlayer)
		{
			[audioPlayer stop];
			[audioPlayer release];
		}
		
		String path = Engine::getSingleton()->getFilePath(file);
		NSString* filename = [NSString stringWithUTF8String:path.c_str()];
		NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:filename, [[NSBundle mainBundle] resourcePath]]];
		
		NSError *error;
		audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
		audioPlayer.numberOfLoops = loop ? -1 : 1 ;
		
		if (audioPlayer == nil)
			ErrorLogger::getLogger()<<"Error Creating AVAudioPlayer\n";
		else
			[audioPlayer play];
	
	}
	
	void AudioEngineIPhone::handleInterruption()
	{		
		context = alcGetCurrentContext();
		alcMakeContextCurrent(NULL);	
		[audioPlayer pause];
	}
	
	void AudioEngineIPhone::endInterruption()
	{
		alcMakeContextCurrent(context);		
		[audioPlayer play];
	}
	
	void AudioEngineIPhone::stopMusic()
	{
		if (audioPlayer)
		{
			[audioPlayer stop];
			audioPlayer.currentTime = 0;
		}
		
	}
	
	
}